/**
 * 输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字。
 */

let matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

let spiralOrder = function(matrix) {
    let resp = []
    if (!matrix.length) {
        return resp;
    }
    let [right, bottom, left, top] = [matrix[0].length - 1, matrix.length - 1, 0, 0];
    while (top <= bottom && left <= right) {
        // 从左向右
        for (let i = left; i <= right; i++) {
            resp.push(matrix[top][i]);
        }
        top++; // top下移一行

        // 从上到下
        for (let i = top; i <= bottom; i++) {
            resp.push(matrix[i][right]);
        }
        right--; // right左移一列

        // 从右向左
        for (let i = right; i >= left && top <= bottom; i--) {
            resp.push(matrix[bottom][i]);
        }
        bottom--; // bottom上移一行

        // 从下向上
        for (let i = bottom; i >= top && left <= right; i--) {
            resp.push(matrix[i][left]);
        }
        left++;
    }
    return resp;
};

// 测试算法
let resp = spiralOrder(matrix)
console.log(resp)